# Import required modules
from __future__ import annotations
import os
import sys
from typing import List, Dict, Any, Optional

# Add project root directory to system path
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.abspath(os.path.join(current_dir, "..", ".."))
sys.path.append(project_root)

class Course:
    """Course class for managing course information, students, and assignments"""
    
    def __init__(self, ID: str, Teacher, CourseName: str, CourseTime: str, Classroom: str, 
                 Students: Optional[List] = None, Assignments: Optional[List] = None, introduction: str = ""):
        # Validate teacher role
        if not hasattr(Teacher, 'role') or Teacher.role != "Teacher":
            raise TypeError("Teacher must have 'role' attribute set to 'Teacher'")
            
        self.ID = ID
        self.Teacher = Teacher  # Teacher object with Teacher role
        self.CourseName = CourseName
        self.CourseTime = CourseTime
        self.Classroom = Classroom
        self.Students = Students if Students is not None else []  # Registered students list
        self.Assignments = Assignments if Assignments is not None else []  # Assignments list
        self.introduction = introduction
    
    def add_student(self, student) -> bool:
        """Add student to course - returns True if successful, False otherwise"""
        from User.Student import Student
        if not isinstance(student, Student):
            return False
        if student not in self.Students:
            self.Students.append(student)
            return True
        return False
    
    def remove_student(self, student) -> bool:
        """Remove student from course - returns True if successful, False otherwise"""
        from User.Student import Student
        if not isinstance(student, Student):
            return False
        if student in self.Students:
            self.Students.remove(student)
            return True
        return False
    
    def add_assignment(self, assignment) -> None:
        """Add assignment to course if it's a valid Assignment object not already in the list"""
        from Assignment.Assignment import Assignment
        if isinstance(assignment, Assignment) and assignment not in self.Assignments:
            self.Assignments.append(assignment)
    
    def get_assignment_by_id(self, assignment_id: str):
        """Find and return assignment by ID or None if not found"""
        from Assignment.Assignment import Assignment  # Local import to avoid circular dependency
        for assignment in self.Assignments:
            if assignment.ID == assignment_id:
                return assignment
        return None
    
    def get_student_progress(self, student) -> Dict[str, Any]:
        """Get student's progress metrics for this course"""
        from User.Student import Student
        if not isinstance(student, Student):
            return {"error": "Invalid student object"}
            
        total_assignments = len(self.Assignments)
        submitted_assignments = sum(1 for a in self.Assignments if a.is_submitted_by(student))
        
        # Calculate average score if available
        scores = []
        for assignment in self.Assignments:
            submission = assignment.get_submission_by_student(student)
            if submission and submission.grade is not None:
                scores.append(submission.grade)
        avg_score = sum(scores) / len(scores) if scores else None
        
        # Get last active submission time
        last_active = None
        if submitted_assignments > 0:
            submissions = [a.get_submission_by_student(student) for a in self.Assignments 
                          if a.get_submission_by_student(student)]
            last_active = max(s.submitted_at for s in submissions)
        
        return {
            "course_id": self.ID,
            "course_name": self.CourseName,
            "total_assignments": total_assignments,
            "submitted_assignments": submitted_assignments,
            "completion_rate": submitted_assignments / total_assignments if total_assignments > 0 else 0,
            "average_score": avg_score,
            "last_active": last_active.strftime("%Y-%m-%d %H:%M") if last_active else None
        }
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert course information to dictionary for data persistence"""
        return {
            "id": self.ID,
            "teacher_id": self.Teacher.ID,
            "course_name": self.CourseName,
            "course_time": self.CourseTime,
            "classroom": self.Classroom,
            "student_ids": [s.ID for s in self.Students],
            "assignment_ids": [a.ID for a in self.Assignments],
            "introduction": self.introduction
        }